﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Revit;
using HYElectricDim;
using YRevitJig;
using YJKRGeometry;
using HYView;

namespace ElectricDim
{
	[Regeneration(RegenerationOption.Manual)]
	[Transaction(TransactionMode.Manual)]
	public class CmdBoxDim : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
			Document document = activeUIDocument.Document;
			if (!(document.ActiveView is ViewPlan))
			{
				Result result = SwitchView.SetUsableView((CmdViewType)3, commandData);
				if (result != Result.Succeeded)
				{
					return result;
				}
			}
			ElectricalUtils.ViewValidating(document);
			WindowHandle windowHandle = null;
			if (windowHandle == null)
			{
				windowHandle = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			}
			DlgBoxNumDim instance = DlgBoxNumDim.GetInstance(commandData.Application, windowHandle);
			instance.Show(windowHandle);
			double num = (double)document.ActiveView.Scale;
			new SubTransaction(activeUIDocument.Document);
			for (;;)
			{
				Transaction transaction = new Transaction(document, "LayLabel");
				try
				{
					transaction.Start();
					Reference reference = activeUIDocument.Selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, new EletricBox());
					Element element = document.GetElement(reference);
					if (element != null)
					{
						XYZ xyz = new XYZ(reference.GlobalPoint.X, reference.GlobalPoint.Y, document.ActiveView.SketchPlane.GetPlane().Origin.Z);
						ElementIdDate elementIdDate = Assist.ExtensibleStorageManager.ReadFromElement<ElementIdDate>(element, this.guid);
						if (elementIdDate.GetId().IntegerValue != 0)
						{
							try
							{
								document.Delete(elementIdDate.GetId());
							}
							catch
							{
							}
						}
						FilteredElementCollector filteredElementCollector = new FilteredElementCollector(document);
						filteredElementCollector.OfClass(typeof(IndependentTag));
						foreach (Element element2 in filteredElementCollector.ToElements())
						{
							if (((IndependentTag)element2).TaggedLocalElementId.IntegerValue == element.Id.IntegerValue)
							{
								document.Delete(element2.Id);
							}
						}
						if (instance.GetLabelType() == LabelType.FromText)
						{
							element.GetParameter(BuiltInParameter.RBS_ELEC_PANEL_NAME).Set(instance.Label);
						}
                        Autodesk.Revit.DB.ElementType elementType = instance.GetElementType();
						ElementSet elementSet = new ElementSet();
						Group group = null;
						if (elementType != null)
						{
							ElectricDimJig electricDimJig = new ElectricDimJig(activeUIDocument);
							if (instance.GetDimStyle() == LeaderStyle.Orthogonal)
							{
								electricDimJig.ResetPoint = XUiJigBase.EResetPoint.eByOrtho;
							}
							electricDimJig.RectWidth = AssistFunc.mmToFeet(8.0) * num;
							electricDimJig.RectHeight = AssistFunc.mmToFeet(4.0) * num;
							XYZ xyz2 = electricDimJig.PickDimPoint(xyz, ElectricDimJig.EDimType.eBottomCorner, "请拾取标注点:");
							electricDimJig.Dispose();
							if (xyz2 == null || xyz2.DistanceTo(xyz) < 0.005)
							{
								transaction.RollBack();
								break;
							}
							IndependentTag independentTag = document.Create.NewTag(document.ActiveView, element, false, 0, 0, xyz2);
							independentTag.ChangeTypeId(elementType.Id);
							LeaderStyle dimStyle = instance.GetDimStyle();
							if (dimStyle == LeaderStyle.HasLeader || dimStyle == LeaderStyle.Orthogonal)
							{
								independentTag.LeaderEndCondition = (LeaderEndCondition)1;
								BoundingBoxXYZ boundingBoxXYZ = independentTag.get_BoundingBox(document.ActiveView);
								XYZ xyz3 = new XYZ(boundingBoxXYZ.Min.X, boundingBoxXYZ.Min.Y, xyz.Z);
								double num2 = 0.5;
								XYZ ePoint;
								if (Geometry.LessThan(xyz2.X, xyz.X))
								{
									ePoint = new XYZ(2.0 * boundingBoxXYZ.Min.X - boundingBoxXYZ.Max.X - 1.0, boundingBoxXYZ.Min.Y, xyz.Z);
									num2 = 2.0 * boundingBoxXYZ.Min.X - boundingBoxXYZ.Max.X - xyz2.X - 0.5;
								}
								else
								{
									ePoint = new XYZ(boundingBoxXYZ.Max.X + 1.0, boundingBoxXYZ.Min.Y, xyz.Z);
								}
								DetailLine detailLine = YJKRevitTools.DrawDetailLine(document, xyz, xyz3);
								DetailLine detailLine2 = YJKRevitTools.DrawDetailLine(document, xyz3, ePoint);
								elementSet.Insert(detailLine);
								elementSet.Insert(detailLine2);
								PointStyle dimLinkStyle = instance.GetDimLinkStyle();
								if (dimLinkStyle == PointStyle.Circle)
								{
									double radius = AssistFunc.mmToFeet(100.0);
									Arc arc = document.CreatYJKArc(xyz, radius, 0.0, Math.PI, XYZ.BasisX, XYZ.BasisY);
									Arc arc2 = document.CreatYJKArc(xyz, radius, Math.PI, Math.PI*2, XYZ.BasisX, XYZ.BasisY);
									DetailCurve detailCurve = document.Create.NewDetailCurve(document.ActiveView, arc);
									DetailCurve detailCurve2 = document.Create.NewDetailCurve(document.ActiveView, arc2);
									elementSet.Insert(detailCurve);
									elementSet.Insert(detailCurve2);
									ElementId hatch = ElectricalUtils.GetHatch(document);
									List<CurveLoop> list = new List<CurveLoop>();
									CurveLoop curveLoop = new CurveLoop();
									curveLoop.Append(arc);
									curveLoop.Append(arc2);
									list.Add(curveLoop);
									FilledRegion filledRegion = FilledRegion.Create(document, hatch, document.ActiveView.Id, list);
									elementSet.Insert(filledRegion);
								}
								else if (dimLinkStyle == PointStyle.Arrow)
								{
									XYZ point = (xyz3 - xyz).Normalize();
									Transform transform = Transform.CreateRotationAtPoint(XYZ.BasisZ, AssistFunc.AngleToRadian(15.0), XYZ.Zero);
									XYZ xyz4 = ElectricalUtils.TransformPoint(point, transform);
									XYZ xyz5 = xyz + xyz4;
									Transform transform2 = Transform.CreateRotationAtPoint(XYZ.BasisZ, AssistFunc.AngleToRadian(-30.0), XYZ.Zero);
									xyz4 = ElectricalUtils.TransformPoint(xyz4, transform2);
									XYZ xyz6 = xyz + xyz4;
									Line line = Line.CreateBound(xyz, xyz5);
									Line line2 = Line.CreateBound(xyz5, xyz6);
									Line line3 = Line.CreateBound(xyz6, xyz);
									List<CurveLoop> list2 = new List<CurveLoop>();
									ElementId hatch2 = ElectricalUtils.GetHatch(document);
									CurveLoop curveLoop2 = new CurveLoop();
									curveLoop2.Append(line);
									curveLoop2.Append(line2);
									curveLoop2.Append(line3);
									list2.Add(curveLoop2);
									FilledRegion filledRegion2 = FilledRegion.Create(document, hatch2, document.ActiveView.Id, list2);
									elementSet.Insert(filledRegion2);
								}
								ElementTransformUtils.MoveElement(document, independentTag.Id, new XYZ(num2, 0.0, 0.0));
								transaction.Commit();
								Transaction transaction2 = new Transaction(document, "Group");
								transaction2.Start();
								group = document.CreatYJKGroup(elementSet);
								transaction2.Commit();
							}
							else
							{
								transaction.Commit();
							}
						}
						else
						{
							transaction.Commit();
						}
						if (group != null && group.IsValidObject)
						{
							ElementIdDate obj = new ElementIdDate(group.Id);
							Assist.ExtensibleStorageManager.WriteToElement(element, this.guid, obj);
						}
						continue;
					}
					transaction.RollBack();
				}
				catch (Exception)
				{
					instance.Close();
					transaction.RollBack();
					return Autodesk.Revit.UI.Result.Succeeded;
				}
				break;
			}
			instance.Close();
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private Guid guid = new Guid("356cda5a-e6c7-4c2f-a9ef-b1713137b8c8");
	}
}
